<?php

namespace App\Imports;

use App\Models\UserGroup;
use App\Models\XXlBaseForm;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\ToCollection;

class RedBookClueImport implements ToCollection
{

    const FIELDS = ["页面ID",
        "页面URL",
        "表单提交时间",
        "来源渠道",
        "广告计划ID",
        // "广告计划名称",
        "广告单元ID",
        // "广告单元名称",
        "广告创意ID"];

    /**
     * @param Collection $collection
     */
    public function collection(Collection $collection)
    {
        $header = null;
        foreach ($collection as $item) {
            if (!$header) {
                $header = $item;
                continue;
            }
            $r = [];
            $question = [];
            foreach ($item as $index => $value) {
                if ($value) {
                    $key = $header[$index];
                    if (preg_match("/手机号/", $key)) {
                        $r['phone'] = $value;
                    } else if (preg_match("/姓名/", $key)) {
                        $r['name'] = $value;
                    } else {
                        if (in_array($key, self::FIELDS))
                            $r[$key] = $value;
                        else
                            $question[$key] = $value;
                    }
                }
            }
            $date = data_get($r, '表单提交时间');
            $phone = data_get($r, 'phone');
            if (!$phone || !$date)
                continue;

            $id = implode(
                '', [data_get($r, '页面ID', ''),
                    data_get($r, '广告计划ID', ''),
                    data_get($r, '广告单元ID', ''),
                    data_get($r, '广告创意ID', ''), $phone]
            );
            $leadsId = md5($id);
            $group = UserGroup::query()
                ->where('name', 'like', '%小红书%')
                ->first();
            try {
                $model = XXlBaseForm::updateOrCreate([
                    'leads_id' => $leadsId,
                ], [
                    'name' => data_get($r, 'name', 'Noname'),
                    'phone' => $phone,
                    'group_id' => data_get($group, 'id'),
                    'channel' => '小红书',
                    'question_data' => $question,
                    'created_at' => $date,
                ]);

            } catch (\Exception $exception) {
                Log::error("save 错误", [
                    $r, $question
                ]);
                throw $exception;
            }
        }
    }
}
